<template>
    <div class="wrap"
         v-loading="loading"
         element-loading-text="处理中...">
        <div class="header tc bdb">
            <span>AI智能出题</span>
            <el-button class="header__btn"
                       type="primary"
                       size="normal"
                       icon="el-icon-plus"
                       :loading="createLoading"
                       @click="toStart">开始出题</el-button>
        </div>
        <ul v-if="list.length"
            class="main">
            <li v-for="(item,index) in list"
                :key="index"
                :class="{err: item.qa_string || item.choices_string}">
                <p>
                    <template v-if="item.question">
                        {{index + 1}}、{{item.question}}
                    </template>
                    <template v-else>
                        {{errMsgHandle(item.qa_string)}}
                    </template>
                </p>
                <div class="choices mui-flex">
                    <template v-if="!item.choices_string">
                        <span v-for="(an,index2) in item.choices"
                              :key="index2"
                              class="mui-flex__cell"
                              :class="{active: index2 === item.answer && item.read}">{{index2}}.{{an}}</span>
                    </template>
                    <p v-else>{{errMsgHandle(item.choices_string)}}</p>
                </div>
                <div v-show="item.extend"
                     class="descript">
                    <div>正确答案：<span>{{item.answer}}</span></div>
                    <div style="margin: 5px 0;">知识点：<span>{{item.type}}</span></div>
                    <p><span>{{item.analysis}}</span></p>
                    <el-button class="close"
                               icon="el-icon-close"
                               type="text"
                               @click="item.extend = false;item.read = false"></el-button>

                </div>
                <div class="btn">
                    <el-button class="view"
                               type="primary"
                               icon="el-icon-view"
                               circle
                               @click="viewDetail(item)"></el-button>
                    <el-button class="edit"
                               type="primary"
                               icon="el-icon-edit"
                               circle
                               @click="toEdit(item,index)"></el-button>
                    <el-button class="del"
                               type="danger"
                               icon="el-icon-delete"
                               circle
                               @click="toDelete(item,index)"></el-button>
                </div>
                <el-tooltip v-if="item.qa_string || item.choices_string"
                            effect="dark"
                            placement="top">
                    <div slot="content">{{errTip(item)}}</div>
                    <el-button class="tip"
                               type="text"
                               icon="el-icon-warning"
                               @click="toEdit(item,index)"></el-button>
                </el-tooltip>

            </li>
        </ul>
        <el-empty v-else
                  description="您还没有生成题目"
                  style="padding-top: 147px;"></el-empty>
        <el-dialog title="开始出题"
                   :visible.sync="isAdd"
                   :close-on-click-modal="false"
                   @close="addFormReset('addForm')"
                   width="600px">
            <el-form :model="addForm"
                     ref="addForm"
                     :rules="addFormRules"
                     label-width="130px"
                     class="demo-ruleForm">
                <el-form-item label="出题量">
                    <el-radio-group v-model="addForm.count">
                        <el-radio label="1">单题</el-radio>
                        <el-radio label="2">套题</el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="addForm.count === '1'">
                    <el-form-item label="题型"
                                  prop="type">
                        <el-select v-model="addForm.type"
                                   placeholder="请选择题型"
                                   style="width: 300px;">
                            <el-option v-for="(item,index) in typeDict"
                                       :key="index"
                                       :label="item"
                                       :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="场景"
                                  prop="scence">
                        <el-select v-model="addForm.scence"
                                   placeholder="请选择场景"
                                   style="width: 300px;">
                            <el-option v-for="item in scenceDict"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                </template>
            </el-form>
            <span slot="footer"
                  class="dialog-footer">
                <el-button @click="addFormReset('addForm')">取 消</el-button>
                <el-button type="primary"
                           @click="addFormSubmit('addForm')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="编辑"
                   :visible.sync="isEdit"
                   :close-on-click-modal="false"
                   @close="editFormReset('editForm')"
                   width="800px">
            <el-form :model="editForm"
                     ref="editForm"
                     :rules="editFormRules"
                     label-width="130px"
                     class="demo-ruleForm">
                <el-form-item label="题目"
                              prop="question">
                    <el-input type="textarea"
                              style="width: 580px;"
                              placeholder="题目"
                              :autosize="{ minRows: 2,maxRows: 5}"
                              v-model.trim="editForm.question"
                              size="normal"></el-input>
                </el-form-item>
                <el-form-item label="选项"
                              prop="choices">
                    <div v-for="(item,key) in editForm.choices"
                         :key="key"
                         class="option">
                        <span>{{key}}.</span>
                        <el-input class="option__input"
                                  style="width: 580px;"
                                  :placeholder="`选项${key}`"
                                  v-model.trim="editForm.choices[key]"
                                  size="normal"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="正确选项"
                              prop="answer">
                    <el-radio-group v-model="editForm.answer"
                                    style="width: 580px;"
                                    placeholder="正确选项">
                        <el-radio v-for="(val,key) in editForm.choices"
                                  :key="key"
                                  :label="key">{{key}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="analysis"
                              label="答案解析">
                    <el-input type="textarea"
                              style="width: 580px;"
                              placeholder="解析"
                              v-model.trim="editForm.analysis"
                              :autosize="{ minRows: 2,maxRows: 6}"></el-input>
                </el-form-item>
                <el-form-item v-if="editForm.choices_string"
                              prop=""
                              label="错误信息">
                    <ul class="err-tip">
                        <li v-if="editForm.qa_string">
                            <strong>题目(解析)错误：</strong>
                            <p>
                                {{editForm.qa_string}}
                            </p>
                        </li>
                        <li v-if="editForm.choices_string">
                            <strong>选项错误：</strong>
                            <p>
                                {{editForm.choices_string}}
                            </p>
                        </li>
                    </ul>
                </el-form-item>

            </el-form>

            <span slot="footer"
                  class="dialog-footer">
                <el-button @click="editFormReset('editForm')">取 消</el-button>
                <el-button type="primary"
                           @click="editFormSubmit('editForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { gen_question, gen_multiple_questions, delete_question, get_question_type_list, save_question } from 'api/home';
export default {
    components: {},
    data() {
        const validateChoices = (rule, value, callback) => {
            const { A, B, C, D } = this.editForm.choices;
            if (A && B && C && D) {
                callback();
            } else {
                callback(new Error('选项不能为空'));
            }
        };
        return {
            loading: false,
            createLoading: false,
            list: [
            ],
            addForm: {
                count: '1',
                type: ''
            },
            addFormRules: {
                type: [
                    { required: true, message: '请选择题型', trigger: 'change' }
                ]
            },
            // 编辑
            editForm: {
                question: '',
                answer: '',
                analysis: ''
            },
            editFormRules: {
                question: [
                    { required: true, message: '题目内容不能为空', trigger: 'blur' }
                ],
                choices: [
                    { required: true, message: '选项不能为空', trigger: 'blur' },
                    { validator: validateChoices, trigger: 'blur' }
                ],
                answer: [
                    { required: true, message: '正确答案不能为空', trigger: 'change' }
                ],

                analysis: [
                    { required: true, message: '题目答案解析不能为空', trigger: 'blur' }
                ]
            },
            isAdd: false,
            isEdit: false,
            editIndex: '',
            typeDict: [], // 题型字典
            scenceDict: [] // 场景字典
        };
    },
    computed: {},
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.getQuestionType();
        },
        // 获取题型
        async getQuestionType() {
            this.loading = true;
            const { code, data } = await get_question_type_list();
            this.loading = false;
            if (code === 200) {
                this.typeDict = data;
            }
        },
        toStart() {
            this.isAdd = true;
        },
        // 添加题型
        addFormSubmit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.isAdd = false;
                    this.createLoading = true;
                    const fn = this.addForm.count !== '1' ? gen_multiple_questions : gen_question;
                    const { code, data } = await fn(this.addForm);
                    this.createLoading = false;
                    if (code === 200) {
                        let arr = [];
                        if (Array.isArray(data)) {
                            arr = data;
                        } else {
                            arr.push(data);
                        }
                        arr.forEach(item => {
                            item.read = false;
                            item.extend = false;
                        });
                        this.list = [...this.list, ...arr];
                        console.log(this.list, 'list');
                        this.addFormReset(formName);
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addFormReset(formName) {
            this.isAdd = false;
            this.editIndex = -1;
            this.addForm = {
                count: '1',
                type: ''
            };
            this.$refs[formName].resetFields();
        },
        viewDetail(item) {
            item.extend = !item.extend;
            console.log(item.extend, 'item.extend');
            item.read = item.extend;
        },
        toEdit(item, index) {
            const data = JSON.parse(JSON.stringify(item));
            if (!data.choices.A && !data.choices.a) {
                data.choices = {
                    A: '',
                    B: '',
                    C: '',
                    D: ''
                };
            }
            this.editForm = data;
            this.isEdit = true;
            this.editIndex = index;
        },
        // 删除
        async toDelete({ question_id }, index) {
            const { code } = await delete_question({
                question_id
            });
            if (code === 200) {
                this.list.splice(index, 1);
                this.$msg.success('删除成功！');
            }
        },
        // 修改题型
        editFormSubmit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.loading = true;
                    const { question_id } = this.editForm;
                    const editForm = JSON.parse(JSON.stringify(this.editForm));
                    delete editForm.qa_string;
                    delete editForm.choices_string;
                    console.log(editForm, 'editForm');
                    const { code } = await save_question({
                        questionInfo: this.editForm,
                        question_id
                    });
                    this.loading = false;
                    if (code === 200) {
                        this.$msg.success('修改成功！');
                        this.list.splice(this.editIndex, 1, editForm);
                        this.editFormReset(formName);
                        // 也要对本地的数据进行修改
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        editFormReset(formName) {
            this.isEdit = false;
            this.editIndex = -1;
            this.editForm = {};
            this.$refs[formName].resetFields();
        },
        errTip({ qa_string, choices_string }) {
            const msg1 = '题目数据解析失败';
            const msg2 = '选项数据解析失败';
            const errMsgArr = [];
            qa_string && errMsgArr.push(msg1);
            choices_string && errMsgArr.push(msg2);
            return `
            题目生成失败：${errMsgArr.join('、')}，可点击编辑
            `;
        },
        errMsgHandle(text) {
            const maxLen = 100;
            const isB = text.length > maxLen;
            const msg = text.slice(0, maxLen);
            console.log(isB);
            return isB ? msg + '...' : msg;
        }
    }
};
</script>

<style scoped lang="less">
.wrap {
    height: 100%;
    background: #f7f7f7;
    word-break: break-all;
}
.header {
    position: relative;
    height: 60px;
    background: #fff;
    span {
        line-height: 60px;
        font-size: 20px;
    }
    &__btn {
        position: absolute;
        right: 80px;
        top: 50%;
        transform: translateY(-50%);
    }
}
.main {
    overflow-y: auto;
    width: 1000px;
    height: calc(100% - 90px - 20px);
    margin: 30px auto;
    padding: 30px 38px;
    box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.2);
    border-radius: 14px;
    background: #fff;
    li {
        position: relative;
        margin-bottom: 36px;
        &:hover {
            .btn {
                display: block;
            }
        }
        &.err {
            // background: #f56c6c;
        }
        p {
            font-size: 18px;
            line-height: 1.6;
        }
        .choices {
            margin-top: 14px;
            span {
                margin-right: 30px;
                &.active {
                    color: @Primary;
                }
            }
        }
        .btn {
            display: none;
            .edit,
            .view,
            .del {
                position: absolute;
                right: 0;
                top: 20px;
                transform: translateY(-50%);
                font-size: 16px;
            }
            .edit {
                right: 50px;
            }
            .view {
                right: 100px;
            }
        }

        .descript {
            position: relative;
            margin-top: 16px;
            padding: 16px 30px 16px 16px;
            background: #f0f9ff;
            border: 1px solid #b0d7ef;
            font-size: 14px;
            border-radius: 8px;
            color: #555;
            p {
                margin-top: 10px;
                font-size: 14px;
            }
            .close {
                position: absolute;
                right: 10px;
                top: 8px;
                font-size: 20px;
                padding: 0;
                color: #999;
            }
            span {
                color: #4f8bba;
            }
        }
        .tip {
            position: absolute;
            left: -27px;
            top: -6px;
            font-size: 20px;
            color: #f56c6c;
        }
    }
}
.option {
    position: relative;
    margin-bottom: 12px;
    &:nth-last-child(1) {
        margin-bottom: 0;
    }
    /deep/ .el-input__inner {
        padding-left: 39px;
    }
    span {
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
        z-index: 9;
    }
}
.err-tip {
    width: 580px;
    padding: 10px;
    background: #f9c3c3;
    border: 1px solid #f56c6c;
    border-radius: 8px;
    li {
        margin-bottom: 10px;
        &:nth-last-child(1) {
            margin-bottom: 0;
        }
    }
    strong {
        font-weight: bold;
    }
}
</style>
